<template>
  <div class="app-container">
    <!-- 条件查询 -->
    <div style="margin-bottom: 10px;">
      <el-form :inline="true">
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryParam.filters[0].value"
            type="date"
            value-format="timestamp"
          ></el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="是否已发布">
          <el-select v-model="queryParam.filters[1].value" clearable>
            <el-option label="未发布" :value="0" />
            <el-option label="已发布" :value="1" />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="_getExamList"></el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="toolbar">
      <el-button type="primary" @click="handleAddExam">新增</el-button>
      <el-button type="danger" @click="handleDeleteExam" :disabled="!multipleSelection.length"
        >删除</el-button
      >
      <el-button type="primary" @click="_getPublishHistoryList">历史发布</el-button>
    </div>
    <Tabel
      :tableData="tableData"
      :cols="cols"
      :isSelect="true"
      @selection-change="handleSelectionChange"
    >
      <template #operationCol>
        <el-table-column>
          <template slot-scope="{ row }">
            <el-button type="text" @click="handleEditExam(row, 1)">编辑</el-button>
            <!-- <el-button type="text" @click="handleEditExam(row, 2)">详情</el-button> -->
            <el-button type="text" @click="handlePublish(row)">发布试卷</el-button>
          </template>
        </el-table-column>
      </template>
    </Tabel>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParam.pageNumber"
      :limit.sync="queryParam.pageSize"
      @pagination="_getExamList"
    />

    <el-dialog title="发布试卷" :visible.sync="publishVisible">
      <div>
        <el-form ref="piblishForm" :model="publishParam" label-width="80px" :rules="publishRules">
          <el-form-item label="标题" prop="name">
            <el-input v-model="publishParam.name"></el-input>
          </el-form-item>
          <el-form-item label="班级" prop="classId">
            <el-select v-model="publishParam.classId">
              <el-option v-for="(value, key) in classEnum" :key="key" :label="value" :value="+key">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="考试时间" prop="paperPublishedTimeArr">
            <el-date-picker
              v-model="publishParam.paperPublishedTimeArr"
              type="datetimerange"
            ></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="publishVisible = false">取 消</el-button>
        <el-button type="primary" @click="_submitPublish">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="历史发布" :visible.sync="publishListParams.visible">
      <Tabel :tableData="publishListParams.data" :cols="publishListParams.cols">
        <template #operationCol>
          <el-table-column>
            <template slot-scope="{ row }">
              <el-button
                type="text"
                @click="handlePublish(row, true)"
                v-if="row.paperPublished === 1"
                >取消发布</el-button
              >
              <el-button type="text" @click="handlePublish(row)" v-else>发布试卷</el-button>
            </template>
          </el-table-column>
        </template>
      </Tabel>
    </el-dialog>
  </div>
</template>

<script>
  import Tabel from '@/components/Table'
  import {
    getExamList,
    deleteExam,
    publishExamPaper,
    getPublishHistoryList,
    unPublishExamPaper
  } from '@/api/TeachingCenter/examManage'
  import Pagination from '@/components/Pagination'
  import Mixin from './mixin'
  import { mapGetters } from 'vuex'
  import { parseTime } from '@/utils'

  export default {
    name: 'examManage',
    components: { Tabel, Pagination },
    mixins: [Mixin],
    data() {
      return {
        tableData: [],
        multipleSelection: [],
        queryParam: {
          pageNumber: 1,
          pageSize: 10,
          filters: [
            {
              value: '',
              paramName: 'create_time',
              paramOperator: 'EQ'
            },
            {
              value: '',
              paramName: 'status',
              paramOperator: 'EQ'
            }
          ]
        },
        total: 0,
        publishParam: {
          classId: null,
          createUser: null,
          examPaperId: null,
          paperPublished: 1,
          paperPublishedTimeArr: [new Date().getTime(), new Date().getTime()]
        },
        publishVisible: false,
        publishRules: {
          name: [{ required: 'true', message: '请输入标题' }],
          classId: [{ required: 'true', message: '请选择班级' }]
        },
        publishListParams: {
          data: [],
          cols: [
            {
              key: 'classId',
              label: '班级ID'
            },
            {
              key: 'name',
              label: '试卷名称'
            },
            {
              key: 'examPaperId',
              label: '试卷ID'
            },
            {
              key: 'paperPublished',
              label: '发布状态',

              formatter: (row) => {
                const arr = ['未发布', '已发布', '取消发布']
                return arr[row.paperPublished] || '未知'
              }
            },
            {
              key: 'paperPublishedTime',
              label: '更新时间',
              formatter: (row) => {
                return parseTime(row.paperPublishedTime)
              }
            }
          ],
          visible: false
        }
      }
    },
    computed: {
      ...mapGetters(['classEnum'])
    },
    created() {
      this._getExamList()
    },
    methods: {
      async _getExamList() {
        const { filters, ...params } = this.queryParam
        params.filters = filters.filter((item) => {
          return item.value !== ''
        })
        const { data } = await getExamList(params)
        this.total = data.total
        this.tableData = data.records
      },
      async _getPublishHistoryList() {
        const { data } = await getPublishHistoryList({})
        console.log(data);
        this.publishListParams.data = data.records
        this.publishListParams.visible = true
      },
      async handlePublish(row, unPublish) {
        const {
          name,
          id,
          createUser,
          examPaperId,
          paperPublished,
          paperPublishedTime,
          paperPublishedTimeEnd
        } = row
        this.publishParam = {
          name,
          createUser,
          examPaperId: examPaperId || id,
          // paperPublished: paperPublished ? 1 : 0
          paperPublished: 1
        }
        if (paperPublishedTime || paperPublishedTimeEnd) {
          this.publishParam.paperPublishedTimeArr = [paperPublishedTime, paperPublishedTime]
        } else {
          this.publishParam.paperPublishedTimeArr = [new Date().getTime(), new Date().getTime()]
        }
        if (!unPublish) {
          this.publishVisible = true
          return
        }
        await unPublishExamPaper(examPaperId)
        this.$Msg.success('操作成功')
        this._getPublishHistoryList()
      },
      async _submitPublish() {
        this.$confirm('是否发布试卷?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { paperPublishedTimeArr } = this.publishParam
          this.publishParam.paperPublishedTime = paperPublishedTimeArr[0]
          this.publishParam.paperPublishedTimeEnd = paperPublishedTimeArr[1]
          console.log(this.publishParam);
          console.log(this.classEnum);
          await publishExamPaper(this.publishParam)
          this.$Msg.success('发布成功')
          this._getPublishHistoryList()

          this.publishVisible = false
        })
      },
      handleAddExam() {
        this.$router.push({ path: './add', query: { type: 0 } })
      },
      handleEditExam({ id }, type) {
        const pathObj = {
          1: './edit',
          2: './detail'
        }
        this.$router.push({ path: pathObj[type], query: { id, type } })
      },
      handleDeleteExam() {
        this.$confirm('是否进行删除操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const ids = this.multipleSelection.map((item) => item.classNo)
          await deleteExam({ ids })
          this._getExamList()
          this.$Msg.success('删除成功!')
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      }
    }
  }
</script>
